package part02_单例模式;

/**饿汉式（静态代码块）
 * @ClassName: SingletonTest02
 * @Author: AllenSun
 * @Date: 2019/12/4 21:41
 */
public class SingletonTest02 {
    public static void main(String[] args) {
        //优缺点跟之前一样，浪费内存
        Singleton02 instance01=Singleton02.getInstance();
        Singleton02 instance02=Singleton02.getInstance();
        System.out.println(instance01==instance02);
        System.out.println("instance01-hashCode="+instance01.hashCode());
        System.out.println("instance02-hashCode="+instance02.hashCode());
    }
}

class Singleton02{
    //1-构造器私有化
    private Singleton02(){ }
    //2-本类内部创建对象实例
    private static Singleton02 instance;
    //3-在静态代码块中，创建单例对象
    static {
        instance=new Singleton02();
    }
    //4-提供一个公有的静态方法，返回实例对象
    public static Singleton02 getInstance(){
        return instance;
    }
}